package cn.cttic.link.controller;

import java.util.List;
import java.util.regex.Pattern;

import cn.cttic.common.core.exception.link.LinkException;
import cn.cttic.link.api.domain.vo.BaseThirdInterfaceConfigVo;
import cn.cttic.link.api.domain.vo.ThirdDistributeR;
import cn.cttic.link.api.enums.ThirdInterfaceType;
import cn.cttic.link.service.IBaseThirdInterfaceConfigService;
import cn.cttic.link.util.HttpClientUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import lombok.RequiredArgsConstructor;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import cn.cttic.common.idempotent.annotation.RepeatSubmit;
import cn.cttic.common.log.annotation.Log;
import cn.cttic.common.web.core.BaseController;
import cn.cttic.common.mybatis.core.page.PageQuery;
import cn.cttic.common.core.domain.R;
import cn.cttic.common.core.validate.AddGroup;
import cn.cttic.common.core.validate.EditGroup;
import cn.cttic.common.log.enums.BusinessType;
import cn.cttic.common.excel.utils.ExcelUtil;
import cn.cttic.link.api.domain.vo.BaseThirdInterfaceVo;
import cn.cttic.link.api.domain.bo.BaseThirdInterfaceBo;
import cn.cttic.link.service.IBaseThirdInterfaceService;
import cn.cttic.common.mybatis.core.page.TableDataInfo;

/**
 * 请求历史
 * 前端访问路由地址为:/link/thirdInterface
 *
 * @author Times.Studio
 * @date 2024-09-17
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/thirdInterface")
@Slf4j
public class BaseThirdInterfaceController extends BaseController {

    private final IBaseThirdInterfaceService baseThirdInterfaceService;

    private final IBaseThirdInterfaceConfigService baseThirdInterfaceConfigService;

    /**
     * 查询请求历史列表
     */
    @SaCheckPermission("link:thirdInterface:list")
    @GetMapping("/list")
    public TableDataInfo<BaseThirdInterfaceVo> list(BaseThirdInterfaceBo bo, PageQuery pageQuery) {
        return baseThirdInterfaceService.queryPageList(bo, pageQuery);
    }

    /**
     * 查询请求历史列表
     */
    @SaCheckPermission("link:thirdInterface:list")
    @GetMapping("/releaseTerminal")
    public R<?> releaseTerminal(@RequestParam(value = "imei") String imei) {
        try {
            log.info("[发行接口][释放终端][开始]");
            BaseThirdInterfaceConfigVo config = baseThirdInterfaceConfigService.getInterfaceConfig(ThirdInterfaceType.DISTRIBUTE_RELEASE_TERMINAL.getValue());

            String imeiVal = StrUtil.fillBefore(imei, '0', 15);

            String url = config.getAccessUrl();
            url += "/" + imeiVal;
            log.info("[发行接口][释放终端][请求地址]: {}", url);
            String result = HttpClientUtil.get(url);
            log.info("[发行接口][释放终端][返回内容]: {}", result);

            BaseThirdInterfaceBo interfaceBo = new BaseThirdInterfaceBo();
            interfaceBo.setBusinessId("");
            interfaceBo.setInterfaceType(ThirdInterfaceType.DISTRIBUTE_RELEASE_TERMINAL.getValue());
            interfaceBo.setAccessUrl(url);
            interfaceBo.setRequestType("GET");
            interfaceBo.setRequestBody("");
            interfaceBo.setResponseBody(result);

            if (!baseThirdInterfaceService.insertByBo(interfaceBo)) {
                throw new LinkException("释放终端 - 录入接口数据失败");
            }
            log.info("[发行接口][释放终端][保存记录完成]");

            ThirdDistributeR r = JSON.parseObject(result, ThirdDistributeR.class);
            return R.ok(r);
        } catch (Exception e) {
            throw new LinkException(e.getMessage());
        }
    }

    /**
     * 导出请求历史列表
     */
    @SaCheckPermission("link:thirdInterface:export")
    @Log(title = "请求历史", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(BaseThirdInterfaceBo bo, HttpServletResponse response) {
        List<BaseThirdInterfaceVo> list = baseThirdInterfaceService.queryList(bo);
        ExcelUtil.exportExcel(list, "请求历史", BaseThirdInterfaceVo.class, response);
    }

    /**
     * 获取请求历史详细信息
     *
     * @param id 主键
     */
    @SaCheckPermission("link:thirdInterface:query")
    @GetMapping("/{id}")
    public R<BaseThirdInterfaceVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable String id) {
        return R.ok(baseThirdInterfaceService.queryById(id));
    }

    /**
     * 新增请求历史
     */
    @SaCheckPermission("link:thirdInterface:add")
    @Log(title = "请求历史", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody BaseThirdInterfaceBo bo) {
        return toAjax(baseThirdInterfaceService.insertByBo(bo));
    }

    /**
     * 修改请求历史
     */
    @SaCheckPermission("link:thirdInterface:edit")
    @Log(title = "请求历史", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody BaseThirdInterfaceBo bo) {
        return toAjax(baseThirdInterfaceService.updateByBo(bo));
    }

    /**
     * 删除请求历史
     *
     * @param ids 主键串
     */
    @SaCheckPermission("link:thirdInterface:remove")
    @Log(title = "请求历史", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable String[] ids) {
        return toAjax(baseThirdInterfaceService.deleteWithValidByIds(List.of(ids), true));
    }
}
